﻿using BaseUI;
using BLL;
using System;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.BusinessExpansion.Templete
{
    public partial class Sys_UserManage : BasePage
    {
        private Sys_UserBLL sub = new Sys_UserBLL();
        private Sys_CompanyBLL scb = new Sys_CompanyBLL();
        private Sys_DepartmentBLL sdb = new Sys_DepartmentBLL();
        private static DataTable dtCompany = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCompany();

                if (Session["UserBufferMemory2"] != null)
                {
                    ddlDept.SelectedValue = Session["UserBufferMemory2"].ToString();
                }
                if (Session["UserBufferMemory3"] != null)
                {
                    ddlWorkState.SelectedValue = Session["UserBufferMemory3"].ToString();
                }
                if (Session["UserBufferMemory4"] != null)
                {
                    ddlLogonState.SelectedValue = Session["UserBufferMemory4"].ToString();
                }
                if (Session["UserBufferMemory5"] != null)
                {
                    txtUserName.Text = Session["UserBufferMemory5"].ToString();
                }

                if (Session["UserBufferMemory1"] != null)
                {
                    BindData(true);
                }

                //初始化GridView数据
                BindProjectName(false);
            }
        }

        private void setList(DataTable dt, System.Web.UI.WebControls.DropDownList lb)
        {
            int idx = -1;
            dtCompany = dt;
            for (int n = 0; n < dtCompany.Rows.Count; n++)
            {
                if (dtCompany.Rows[n]["CMY_PARENTID"].ToString() == "0")
                {
                    idx = idx + 1;
                    addItem(lb, dtCompany.Rows[n]["CMY_ID"].ToString(), dtCompany.Rows[n]["CMY_NAME"].ToString(), idx);
                    idx = idx - 1;
                }
            }
        }

        private void addItem(System.Web.UI.WebControls.DropDownList lb, String sId, String sName, int idx)
        {
            String sn = sName;
            for (int n = 0; n < idx; n++)
            {
                sn = (char)58853 + "" + sn;
            }
            System.Web.UI.WebControls.ListItem it = new ListItem(sn, sId);

            lb.Items.Add(it);

            for (int n = 0; n < dtCompany.Rows.Count; n++)
            {
                if (dtCompany.Rows[n]["CMY_PARENTID"].ToString() == sId)
                {
                    idx = idx + 1;
                    addItem(lb, dtCompany.Rows[n]["CMY_ID"].ToString(), dtCompany.Rows[n]["CMY_NAME"].ToString(), idx);
                    idx = idx - 1;
                }
            }
        }

        private void BindCompany()
        {
            //公司
            DataTable dataCompany = scb.GetInfoByPId((int)lognUser.USER_COMPANY);
            //setList(dataCompany, ddlCompany);
            ddlCompany.DataSource = dataCompany;
            ddlCompany.DataTextField = "CMY_NAME";
            ddlCompany.DataValueField = "CMY_ID";
            ddlCompany.DataBind();
            ddlCompany.Items.Insert(0, new ListItem("---请选择---", "-1"));
            ddlCompany.SelectedValue = CurrentUserCompanyID.ToString();

            if (Session["UserBufferMemory1"] != null)
            {
                ddlCompany.SelectedValue = Session["UserBufferMemory1"].ToString();
            }

            //部门
            DataTable dtDept = sdb.GetInfoALLCmyID(ddlCompany.SelectedValue);
            ddlDept.DataSource = dtDept;
            ddlDept.DataTextField = "DEPTNAME";
            ddlDept.DataValueField = "DEPTID";
            ddlDept.DataBind();
            ddlDept.Items.Insert(0, new ListItem("---请选择---", "-1"));
            ddlDept.SelectedValue = "-1";

            ////职位
            //DataTable dtPosition = sdb.PositionSelect(ddlDept.SelectedValue);

            //ddlPosition.DataSource = dtPosition;
            //ddlPosition.DataTextField = "C_positionName";
            //ddlPosition.DataValueField = "N_positionId";
            //ddlPosition.DataBind();
            //ddlPosition.Items.Insert(0, new ListItem("---请选择---", "-1"));
            //ddlPosition.SelectedValue = "-1";
        }

        private void Bind()
        {
            ViewState["Where"] = "";

            //BindData(true);
        }

        private void BindData(bool isFirst)
        {
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = "";
            }

            int rowcount = 0;
            if (isFirst)
            {
                PageIng.CurrentPage = 1;
            }
            //获取所有行。
            //rowcount="SELECT COUNT(*) FROM USER WHERE USER"
            //rowcount = sub.GetRecordCount(lognUser.USER_COMPANY.ToString(), Where);

            DataTable dtItem;
            dtItem = sub.GetListByPage((int)lognUser.USER_COMPANY, "WHERE 1=1" + (Where == "" ? "" : " " + Where), "ORDER BY TT1.USER_ID DESC", (PageIng.CurrentPage - 1) * PageIng.RowsPerPage, PageIng.CurrentPage * PageIng.RowsPerPage, out rowcount);
            //dtItem = sub.GetListByPage(lognUser.USER_COMPANY.ToString(), Where, "USER_ID DESC", PageIng.CurrentPage, PageIng.RowsPerPage);
            /*for (int i = 0; i < dtItem.Rows.Count; i++)
            {
                dtItem.Rows[i]["USER_JOBSTATUS"] = (dtItem.Rows[i]["USER_JOBSTATUS"].ToString() == "1" ? "在职" : "离职");
                dtItem.Rows[i]["USER_LOGINSTATUS"] = (dtItem.Rows[i]["USER_LOGINSTATUS"].ToString() == "1" ? "允许登录" : "禁止登录");
            }*/
            PageIng.Visible = true;
            PageIng.RowsCount = rowcount;
            PageIng.DataSource = dtItem;
            PageIng.GridViewSource = gvUser;
            PageIng.RowsPerPage = PageIng._rowsPerPage;
            PageIng.Bind();
        }

        protected void btnSelect_Click(object sender, EventArgs e)
        {
            NewMethod();
        }

        private void NewMethod()
        {
            string COMPANYID = ddlCompany.SelectedValue.ToString();
            string DEPTID = ddlDept.SelectedValue.ToString();
            // string PositionId = ddlPosition.SelectedValue.ToString();
            string WorkSateId = ddlWorkState.SelectedValue.ToString();
            string LogonSateId = ddlLogonState.SelectedValue.ToString();
            //  string OnlineSateId = ddlOnLineState.SelectedValue.ToString();
            string UserName = txtUserName.Text;

            string whereStr = "";

            if (DEPTID != "-1" && (!string.IsNullOrEmpty(DEPTID)))
            {
                whereStr += "AND TT1.USER_DEPARTMENT=" + DEPTID;
            }
            else
            {
                if (COMPANYID != "-1" && (!string.IsNullOrEmpty(COMPANYID)))
                {
                    /*var sql = string.Format(@"SELECT
	                                            CMY_ID
                                            FROM
	                                            SYS_COMPANY T1 START WITH CMY_ID = {0} CONNECT BY PRIOR CMY_ID = CMY_PARENTID", COMPANYID);
                    whereStr += "AND TT1.USER_COMPANY IN (" + sql + ")";*/
                    whereStr += "AND TT1.USER_COMPANY=" + COMPANYID;
                }
                else
                {
                    var sql = string.Format(@"SELECT
	                                            CMY_ID
                                            FROM
	                                            SYS_COMPANY T1 START WITH CMY_ID = {0} CONNECT BY PRIOR CMY_ID = CMY_PARENTID", CurrentUserCompanyID);
                    whereStr += "AND TT1.USER_COMPANY IN (" + sql + ")";
                }
            }

            if (WorkSateId != "-1" && (!string.IsNullOrEmpty(WorkSateId)))
            {
                whereStr += " AND TT1.USER_JOBSTATUS=" + WorkSateId;
            }
            if (LogonSateId != "-1" && (!string.IsNullOrEmpty(LogonSateId)))
            {
                whereStr += " AND TT1.USER_LOGINSTATUS=" + LogonSateId;
            }
            if ((!string.IsNullOrEmpty(UserName)))
            {
                whereStr += " AND TT1.USER_NAME like '%" + UserName + "%'";
            }
            ViewState["Where"] = whereStr;
            BindData(true);
        }

        protected void btnInsert_Click(object sender, EventArgs e)
        {
            Session["UserBufferMemory1"] = ddlCompany.SelectedValue.ToString();
            Session["UserBufferMemory2"] = ddlDept.SelectedValue.ToString();
            Session["UserBufferMemory3"] = ddlWorkState.SelectedValue.ToString();
            Session["UserBufferMemory4"] = ddlLogonState.SelectedValue.ToString();
            Session["UserBufferMemory5"] = txtUserName.Text;
            MessageBox.ResponseScript(this, "FORM_INSERT();");
            //Response.Redirect("Add_User.aspx");
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            int count = 0;
            string pid = "";
            for (int i = 0; i < gvUser.Rows.Count; i++)
            {
                if (((CheckBox)gvUser.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    count++;
                    pid = ((CheckBox)gvUser.Rows[i].FindControl("chkSelectId")).ToolTip;
                }
            }
            if (count == 1)
            {
                Session["UserBufferMemory1"] = ddlCompany.SelectedValue.ToString();
                Session["UserBufferMemory2"] = ddlDept.SelectedValue.ToString();
                Session["UserBufferMemory3"] = ddlWorkState.SelectedValue.ToString();
                Session["UserBufferMemory4"] = ddlLogonState.SelectedValue.ToString();
                Session["UserBufferMemory5"] = txtUserName.Text;
                MessageBox.ResponseScript(this, "FORM_EDIT(\"" + pid + "\")");
                //Response.Redirect("Upd_User.aspx?id=" + pid);
            }
        }

        protected void btnDelele_Click(object sender, EventArgs e)
        {
            int count = 0;
            string pids = "";
            for (int i = 0; i < gvUser.Rows.Count; i++)
            {
                if (((CheckBox)gvUser.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    count++;
                    pids += ((HiddenField)gvUser.Rows[i].FindControl("HiddID")).Value.ToString() + ",";
                }
            }
            if (count > 0)
            {
                string strids = pids.Substring(0, pids.Length - 1);

                int row = sub.DELETE(strids, lognUser.USER_NAME);
                if (row > 0)
                {
                    MessageBox.Show(Page, "删除成功");
                    Bind();
                    return;
                }
                else
                {
                    MessageBox.Show(Page, "删除失败");
                    return;
                }
            }
        }

        protected void btnSetSignature_Click(object sender, EventArgs e)
        {
            int count = 0;
            string pid = "";
            for (int i = 0; i < gvUser.Rows.Count; i++)
            {
                if (((CheckBox)gvUser.Rows[i].FindControl("chkSelectId")).Checked == true)
                {
                    count++;
                    pid = ((HiddenField)gvUser.Rows[i].FindControl("HiddID")).Value.ToString();
                }
            }
            if (count == 1)
            {
                Response.Redirect("Add_UserSignature.aspx?ID=" + pid);
            }
        }

        protected void PageIng_DataBinding(object sender, EventArgs e)
        {
            BindData(false);
        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            //公司
            //DataTable dtCompany = scb.GetAllInfo();

            //ddlCompany.DataSource = dtCompany;
            //ddlCompany.DataTextField = "CMY_NAME";
            //ddlCompany.DataValueField = "CMY_ID";
            //ddlCompany.DataBind();
            //ddlCompany.Items.Insert(0, new ListItem("---请选择---", "-1"));
            //ddlCompany.SelectedValue = "-1";
            //部门
            DataTable dtDept = sdb.GetInfoALLCmyID(ddlCompany.SelectedValue);

            ddlDept.DataSource = dtDept;
            ddlDept.DataTextField = "DEPTNAME";
            ddlDept.DataValueField = "DEPTID";
            ddlDept.DataBind();
            ddlDept.Items.Insert(0, new ListItem("---请选择---", "-1"));
            ddlDept.SelectedValue = "-1";
        }

        protected void ddlDept_SelectedIndexChanged(object sender, EventArgs e)
        {
            //职位
            //DataTable dtPosition = sdb.PositionSelect(ddlDept.SelectedValue);

            //ddlDept.DataSource = dtPosition;
            //ddlDept.DataTextField = "C_positionName";
            //ddlDept.DataValueField = "N_positionId";
            //ddlDept.DataBind();
            //ddlDept.Items.Insert(0, new ListItem("---请选择---", "-1"));
            //ddlDept.SelectedValue = "-1";
        }

        /// <summary>
        /// GridView 标题排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvUser_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sPage = e.SortExpression;
            string SortOrder, OrderDire;
            SortOrder = ViewState["SortOrder"] == null ? null : (string)ViewState["SortOrder"];
            OrderDire = ViewState["OrderDire"] == null ? null : (string)ViewState["OrderDire"];
            if (SortOrder == sPage)
            {
                if (OrderDire == "Desc")
                    OrderDire = "ASC";
                else
                    OrderDire = "Desc";
            }
            else
            {
                SortOrder = e.SortExpression;
                OrderDire = "ASC";
            }
            ViewState["SortOrder"] = SortOrder;
            ViewState["OrderDire"] = OrderDire;
            BindProjectName(true);
        }

        /// <summary>
        /// 绑定项目名称（非动态）绑定GridView
        /// </summary>
        public void BindProjectName(bool iSsort)
        {
            NewMethod();
            string Where = "";
            try
            {
                Where = ViewState["Where"].ToString();
            }
            catch
            {
                Where = " CMY_ID =" + CurrentUserCompanyID;
            }

            int rowcount = 0;

            DataTable dtItem;
            dtItem = sub.GetListByPage((int)lognUser.USER_COMPANY, "WHERE 1=1" + (Where == "" ? "" : " " + Where), "ORDER BY TT1.USER_ID DESC", (PageIng.CurrentPage - 1) * PageIng.RowsPerPage, PageIng.CurrentPage * PageIng.RowsPerPage, out rowcount);

            for (int i = 0; i < dtItem.Rows.Count; i++)
            {
                dtItem.Rows[i]["USER_ROLEID"] = (dtItem.Rows[i]["USER_ROLEID"].ToString());
                /*dtItem.Rows[i]["USER_JOBSTATUS"] = (dtItem.Rows[i]["USER_JOBSTATUS"].ToString() == "1" ? "在职" : "离职");
                dtItem.Rows[i]["USER_LOGINSTATUS"] = (dtItem.Rows[i]["USER_LOGINSTATUS"].ToString() == "1" ? "允许登录" : "禁止登录");*/
            }

            DataView view = dtItem.DefaultView;
            if (iSsort)
            {
                string sort = (string)ViewState["SortOrder"] + " " + (string)ViewState["OrderDire"];
                view.Sort = sort;//设置排序
            }

            gvUser.DataSource = view;

            gvUser.DataBind();
        }
    }
}